package reesoft.common.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.HttpStatus;

import java.io.IOException;
import java.util.Map;

/**
 * 公用 HTTP 访问单元
 *
 * Created by reesoft on 2017-07-13
 */
public class HttpUtil
{
    /**
     * 向远程服务器提交 HTTP GET 请求并获取字符串类型的结果
     *
     * @param url 请求的地址
     * @return 服务器返回的结果
     */
    public static String get(final String url)
    {
        final HttpClient httpClient = new HttpClient();
        final GetMethod getMethod = new GetMethod(url);
        return getHttpMethodResponse(httpClient, getMethod);
    }

    /**
     * 向远程服务器提交 POST 请求并获取字符串类型的结果
     *
     * @param url 请求的地址
     * @param nameValuePairs 提交的参数名和参数值对集合
     * @return 服务器返回的结果
     */
    public static String post(final String url, final NameValuePair[] nameValuePairs)
    {
        final HttpClient httpClient = new HttpClient();
        final PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestBody(nameValuePairs);
        return getHttpMethodResponse(httpClient, postMethod);
    }

    /**
     * 向远程服务器提交 POST 请求并获取字符串类型的结果
     *
     * @param url 请求的地址
     * @param postParams 提交的参数名和参数值映射
     * @return 服务器返回的结果
     */
    public static String post(final String url, final Map<String, Object> postParams)
    {
        NameValuePair[] nameValuePairs = new NameValuePair[postParams.size()];
        int i = 0;

        for (Map.Entry<String, Object> entry : postParams.entrySet())
        {
            nameValuePairs[i].setName(entry.getKey());
            nameValuePairs[i].setValue(String.valueOf(entry.getValue()));
            i++;
        }

        return post(url, nameValuePairs);
    }

    /**
     * 执行 HTTP 请求并读取结果
     */
    private static String getHttpMethodResponse(final HttpClient httpClient, final HttpMethod httpMethod)
    {
        try
        {
            httpClient.executeMethod(httpMethod);

            switch (httpMethod.getStatusCode())
            {
                case HttpStatus.SC_OK:
                    return httpMethod.getResponseBodyAsString();

                default:
                    break;
            }
        }
        catch (final IOException e)
        {
            //LOG.warning(e.toString());
        }
        finally
        {
            httpMethod.releaseConnection();
        }

        return "";
    }
}
